﻿using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[Serializable]
public class ScriptableObjectDictionary<TKey, TValue> : ScriptableObject
{
    [SerializeField]
    public List<TKey> keys = new List<TKey>();
    [SerializeField]
    public List<TValue> values = new List<TValue>();
    protected Dictionary<TKey, TValue> target;
    public Dictionary<TKey, TValue> Target
    {
        get
        {
            if (target == null)
            {
                target = new Dictionary<TKey, TValue>();

                int cnt = keys.Count;
                if(cnt > 0)
                {

                    for (int i = 0; i < cnt; i++)
                        target[keys[i]] = values[i];
                }
            }

            return target;
        }
        set
        {
            target = value;
            keys = new List<TKey>(Target.Keys);
            values = new List<TValue>(Target.Values);
        }
    }

    public bool Add(TKey key,TValue value)
    {
        TValue tmp;

        if (value == null) return false;

        if (Target.TryGetValue(key,out tmp)) return false;

        //UnityEditor.Undo.RecordObjects(this, "ScriptableObjectDictionary");

        keys.Add(key);
        values.Add(value);

        if (target == null) target = new Dictionary<TKey, TValue>();
        target.Add(key, value);

        return true;
    }

    public bool Del(TKey key)
    {
        if (keys == null) return false;

        TValue tmp;

        if (!target.TryGetValue(key, out tmp)) return false;

        //UnityEditor.Undo.RecordObjects(new UnityEngine.Object[] { this }, "ScriptableObjectDictionary");

        int index = keys.IndexOf(key);
        if (index == -1) return false;

        keys.RemoveAt(index);
        values.RemoveAt(index);
        target.Remove(key);

        return true;
    }

    public List<TKey> GetKeys()
    {
        return keys;
    }

    public int GetIndex(TKey key)
    {
        if (keys == null) return -1;

        return keys.IndexOf(key);
    }


    public void Clear()
    {
        if (null == keys) return;

        keys.Clear();
        values.Clear();
        target.Clear();
    }
}